package p.sglmsn.top.antiduplication.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWarDeployment;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import p.sglmsn.top.antiduplication.handle.DuplicateRequestFiltering;
import p.sglmsn.top.antiduplication.infe.UniqueCertificate;

import java.io.Serializable;

@Configuration
@ConditionalOnBean(UniqueCertificate.class)
@ConditionalOnWebApplication
@Import(SpringUtil.class)
public class DuplicateRequestContent implements WebMvcConfigurer {

    @Autowired
    DuplicateRequestFiltering d;
    @Bean(name = "duplicateRequestFiltering")
    public DuplicateRequestFiltering duplicateRequestFiltering(LettuceConnectionFactory lettuceConnectionFactory, UniqueCertificate uniqueCertificate) {

        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        {
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
            redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        }
        DuplicateRequestFiltering duplicateRequestFiltering = new DuplicateRequestFiltering().setRedisTemplate(redisTemplate).setUniqueCertificate(uniqueCertificate);
        duplicateRequestFiltering.init();
        return duplicateRequestFiltering;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(d).addPathPatterns(StrUtil.isBlank(d.getUniqueCertificate().url()) ? "/**" : d.getUniqueCertificate().url());
        WebMvcConfigurer.super.addInterceptors(registry);
    }
}
